/**
 * Filename: NewsNoticeFragment.java
 * @author  Firefly
 * @contact postfirefly@163.com
 * @time    2016/3/4 12:07
 */
package com.github.postsanf.yinian.fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.OvershootInterpolator;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.github.postsanf.yinian.BaseFragment;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.NewsNoticeAdapter;
import com.github.postsanf.yinian.bean.YNNewsNotice;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.entity.YNCommonResponse;
import com.github.postsanf.yinian.service.NewsService;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.WrapContentLinearLayoutManager;
import com.github.postsanf.yinian.ynlist.EndlessRecyclerOnScrollListener;
import com.github.postsanf.yinian.ynlist.LoadingFooter;
import com.github.postsanf.yinian.ynlist.RecyclerViewStateUtils;
import com.github.postsanf.yinian.ynlist.YNRecyclerViewAdapter;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import jp.wasabeef.recyclerview.animators.FadeInAnimator;
/**
 * 消息-通知
 */
public class NewsNoticeFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {
    private View                        view;
    private NewsNoticeAdapter           mAdapter;
    private RecyclerView                rv_news_list;
    private WrapContentLinearLayoutManager         mLinearLayoutManager;
    private LinkedList<YNNewsNotice>    mNoticeDatas = new LinkedList<>();
    private boolean                     isBottom;
    private SwipeRefreshLayout          mRefreshlayout;
    private Handler                     handler;
    private YNRecyclerViewAdapter       mYNRecyclerViewAdapter;
    private AlertDialog 				alertDialog;

    // 注册广播接收过滤
    private void registerBroadcastReceiver(){
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionNoticeUpdate);
        myIntentFilter.addAction(ACTIONs.actionDoNotice);
        getActivity().registerReceiver(mNewsNoticeBroadcastReceiver, myIntentFilter);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerBroadcastReceiver();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        initData();
        initView();
        return view;
    }

    // 初始化数据
    private void initData(){
        handler        = new Handler();
        mNoticeDatas   = new LinkedList<>();

        // 通知Service初始化通知内容
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                noticeServiceInit();
            }
        }, 500);
    }

    private void initView() {
        view = View.inflate(getActivity(), R.layout.yn_news_list, null);
        rv_news_list    = (RecyclerView) view.findViewById(R.id.rv_news_list);
        mRefreshlayout = (SwipeRefreshLayout) view.findViewById(R.id.news_invite_refresh);
        mRefreshlayout.setColorSchemeColors(getResources().getColor(R.color.yncolor));
        mRefreshlayout.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
                        .getDisplayMetrics()));
        mRefreshlayout.setOnRefreshListener(this);
        // 初始加载刷新
        mRefreshlayout.setRefreshing(true);
        rv_news_list.setHasFixedSize(true);
        mLinearLayoutManager = new WrapContentLinearLayoutManager(getActivity());
        rv_news_list.setLayoutManager(mLinearLayoutManager);
        rv_news_list.setItemAnimator(new FadeInAnimator(new OvershootInterpolator(1f)));
        rv_news_list.getItemAnimator().setAddDuration(300);
        rv_news_list.getItemAnimator().setRemoveDuration(300);
        rv_news_list.getItemAnimator().setMoveDuration(300);
        rv_news_list.getItemAnimator().setChangeDuration(300);
        mAdapter = new NewsNoticeAdapter(getActivity(), mNoticeDatas);
        mYNRecyclerViewAdapter = new YNRecyclerViewAdapter(mAdapter);
        rv_news_list.setAdapter(mYNRecyclerViewAdapter);

        rv_news_list.addOnScrollListener(new EndlessRecyclerOnScrollListener() {
            @Override
            public void onLoadNextPage(View view) {
                super.onLoadNextPage(view);
                // 已经到底，返回
                if (isBottom) {
                    return;
                }
                // 加载中，返回
                LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(rv_news_list);
                if (state == LoadingFooter.State.Loading) {
                    return;
                }
                // 加载下一页
                RecyclerViewStateUtils.setFooterViewState(getActivity(), rv_news_list, 10, LoadingFooter.State.Loading, null);
                rv_news_list.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loadNotices();
                    }
                }, 500);
            }
        });

        mAdapter.setOnItemLongClickListener(new NewsNoticeAdapter.OnItemLongClickListener() {
            @Override
            public void OnItemLongClick(View view, int position) {
                YNNewsNotice item = mNoticeDatas.get(position);
                isSureDelete(position, String.valueOf(item.getNid()));
            }
        });
    }

    // 是否删除通知
    public  void  isSureDelete(final int position,final String  nid)
    {
        View delView = View.inflate(getActivity(),R.layout.yn_common_delete, null);
        LinearLayout ll_delete_news = (LinearLayout)delView.findViewById(R.id.ll_delete_news);
        alertDialog = new AlertDialog.Builder(getActivity()).show();
        alertDialog.setCanceledOnTouchOutside(true);
        alertDialog.setContentView(delView);
        WindowManager.LayoutParams layout= alertDialog.getWindow().getAttributes();
        layout.width = DisplayUtils.getScreenWidthPixels(getActivity()) - DisplayUtils.dp2px(getActivity(), 32*2);
        alertDialog.getWindow().setAttributes(layout);
        // 删除
        ll_delete_news.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteNotice(position, nid);
                alertDialog.dismiss();
            }
        });
    }

    private void loadNotices(){
        if(mNoticeDatas.size()<=0){return;}
        Intent mIntent = new Intent(getActivity(), NewsService.class);
        mIntent.setAction(ACTIONs.actionNoticeNews);
        mIntent.putExtra(ACTIONs.aNeedId, mNoticeDatas.getLast().getNid());
        mIntent.putExtra(ACTIONs.aNeedType, CommonConstants.YNS_SIGN_LOAD);
        getActivity().startService(mIntent);
    }

    public void clearAll(){
        mNoticeDatas.clear();
        mAdapter.notifyDataSetChanged();
    }

    // 删除通知
    private void deleteNotice(final int position,String noticeId)
    {
        LinkedHashMap<String,String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_NOTICE_ID, noticeId);
        StringRequest req = new StringRequest(getString(R.string.BASE_URL)+getString(R.string.ynDeleteNotice))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNCommonResponse resNotice = gson.fromJson(s, YNCommonResponse.class);
                        if (ReqUtils.isSuccess(resNotice.getCode())) {
                            mNoticeDatas.remove(position);
                            mAdapter.notifyDataSetChanged();
                        } else {
                            Toast.makeText(getActivity(), CommonConstants.TIP_UNKNOW, Toast.LENGTH_SHORT).show();
                        }
                    }
                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        Toast.makeText(getActivity(), CommonConstants.YN_NET_LINK, Toast.LENGTH_SHORT).show();
                    }
                });
        liteHttp.executeAsync(req);
    }


    // 更新通知消息
    private void updateView(List<YNNewsNotice>  noticeList ,String direction){
        switch (direction){
            case ACTIONs.aAddTop:
                for (int i=0; i<noticeList.size() ; i++){
                    mNoticeDatas.addFirst(noticeList.get(i));
                }
                break;
            case ACTIONs.aAddBottom:
                for (int i=0; i<noticeList.size() ; i++){
                    mNoticeDatas.addLast(noticeList.get(i));
                }
                if(noticeList.size()==0){
                    isBottom = true;
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), rv_news_list, 10, LoadingFooter.State.TheEnd, null);
                } else {
                    RecyclerViewStateUtils.setFooterViewState(rv_news_list, LoadingFooter.State.Normal);
                }
                mAdapter.notifyDataSetChanged();
                break;
        }
        mRefreshlayout.setRefreshing(false);
        mAdapter.notifyDataSetChanged();
    }

    // 分析并执行动作
    BroadcastReceiver mNewsNoticeBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent){
            String action = intent.getAction();
            switch (action){
                case ACTIONs.actionNoticeUpdate:
                    List<YNNewsNotice> ll_news_notice = (List<YNNewsNotice>) intent.getSerializableExtra(ACTIONs.aAddData);
                    String direction  = intent.getStringExtra(ACTIONs.aAddDirection);
                    updateView(ll_news_notice,direction);
                    break;
                case ACTIONs.actionDoNotice:
                    YNNewsNotice mNotice = (YNNewsNotice) intent.getSerializableExtra(ACTIONs.aNoticeDatas);
                    mNoticeDatas.addFirst(mNotice);
                    mAdapter.notifyDataSetChanged();
                    break;
            }
        }
    };

    // 通知后台初始化数据
    private void noticeServiceInit(){
        if (getActivity()==null){
            return;
        }
        Intent mIntent = new Intent(getActivity(), NewsService.class);
        mIntent.setAction(ACTIONs.actionNoticeNews);
        mIntent.putExtra(ACTIONs.aNeedId, 0);
        mIntent.putExtra(ACTIONs.aNeedType, CommonConstants.YNS_SIGN_INITS);
        getActivity().startService(mIntent);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        getActivity().unregisterReceiver(mNewsNoticeBroadcastReceiver);
    }

    @Override
    public void onRefresh() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mRefreshlayout.setRefreshing(false);
            }
        }, 500);
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("MainScreen");
    }
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("MainScreen");
    }
}